package com.ruoyi.patrol.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.PatrolConstans;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.patrol.domain.PtLineGuard;
import com.ruoyi.patrol.domain.PtLineTask;
import com.ruoyi.patrol.service.IPtLineGuardService;
import com.ruoyi.patrol.service.IPtLineTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 巡查线路与安保人员关联Controller
 *
 * @author lkm
 * @date 2022-11-12
 */
@RestController
@RequestMapping("/patrol/line_guard")
public class PtLineGuardController extends BaseController {
    @Autowired
    private IPtLineGuardService ptLineGuardService;
    @Autowired
    IPtLineTaskService ptLineTaskService;

    /**
     * 查询巡查线路与安保人员关联列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:list')")
    @GetMapping("/list")
    public TableDataInfo list(PtLineGuard ptLineGuard) {
        startPage();
        List<PtLineGuard> list = ptLineGuardService.selectPtLineGuardList(ptLineGuard);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('patrol:line_guard:list')")
    @GetMapping("/list/nopage")
    public List<PtLineGuard> listNoPage() {
        List<PtLineGuard> list = ptLineGuardService.selectPtLineGuardList(new PtLineGuard());
        return list;
    }

    /**
     * 查询保安巡查排班个数,目前PtLineGuard中的参数只支持date,patrolStatus(0、未执行，1、正在进行，2、执行完成)
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:list')")
    @GetMapping("/count")
    public long count(PtLineGuard ptLineGuard) throws ParseException {
        if (ptLineGuard.getDate() == null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            ptLineGuard.setDate(sdf.parse(sdf.format(new Date())));
        }
        return ptLineGuardService.selectCount(ptLineGuard);
    }

    /**
     * 导出巡查线路与安保人员关联列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:export')")
    @Log(title = "巡查线路与安保人员关联", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PtLineGuard ptLineGuard) {
        List<PtLineGuard> list = ptLineGuardService.selectPtLineGuardList(ptLineGuard);
        ExcelUtil<PtLineGuard> util = new ExcelUtil<PtLineGuard>(PtLineGuard.class);
        return util.exportExcel(list, "guard");
    }

    /**
     * 获取巡查线路与安保人员关联详细信息
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ptLineGuardService.selectPtLineGuardById(id));
    }

    /**
     * 新增巡查线路与安保人员关联
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:add')")
    @Log(title = "巡查线路与安保人员关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PtLineGuard ptLineGuard) {
        for (String date : ptLineGuard.getDates()) {
            PtLineGuard query = new PtLineGuard();
            query.setLineId(ptLineGuard.getLineId());
            query.setGroupId(ptLineGuard.getGroupId());
            query.setDate(DateUtils.parseDate(date));
            long count = ptLineGuardService.selectCount(query);
            if (count > 0) {
                return AjaxResult.error("该小组在" + date + "已分配此路线");
            }
        }

        return toAjax(ptLineGuardService.insertPtLineGuard(ptLineGuard));
    }

    /**
     * 修改巡查线路与安保人员关联
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:edit')")
    @Log(title = "巡查线路与安保人员关联", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody PtLineGuard ptLineGuard) {
        PtLineGuard query = new PtLineGuard();
        query.setLineId(ptLineGuard.getLineId());
        query.setGuardId(ptLineGuard.getGuardId());
        query.setDate(ptLineGuard.getDate());
        List<PtLineGuard> list = ptLineGuardService.selectPtLineGuardList(query);
        long count = list.stream().filter(e -> !e.getId().equals(ptLineGuard.getId())).count();
        if (count > 0) {
            return AjaxResult.error("该人员当天已分配此路线");
        }
        return toAjax(ptLineGuardService.updatePtLineGuard(ptLineGuard));
    }

    /**
     * 删除巡查线路与安保人员关联
     */
    @PreAuthorize("@ss.hasPermi('patrol:line_guard:remove')")
    @Log(title = "巡查线路与安保人员关联", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        PtLineGuard ptLineGuard = ptLineGuardService.selectPtLineGuardById(ids[0]);
        if (ptLineGuard.getPatrolStatus() != PatrolConstans.PATROL_SCHEDULE_STATUES_UNDO) {
            return AjaxResult.error("该排班已经开始巡查，不能删除");
        }
        PtLineTask ptLineTask = new PtLineTask();
        ptLineTask.setLineId(ptLineGuard.getLineId());
        ptLineTask.setGroupId(ptLineGuard.getGroupId());
        ptLineTaskService.deletePtLineTaskByLineIdAndGroupId(ptLineTask);
        return toAjax(ptLineGuardService.deletePtLineGuardByIds(ids));
    }
}
